/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.siscoh.controller;

import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.siscoh.model.bean.CategoriaBean;
import org.siscoh.model.bean.EspecificacaoBean;
import org.siscoh.model.bean.ItemBean;
import org.siscoh.model.dao.CategoriaDao;
import org.siscoh.model.dao.ItemDao;

/**
 *
 * @author israel
 */
public class ControladorPeca extends AbstractController {

    @Override
    public String executa(HttpServletRequest request, HttpServletResponse response) {
        String url = "error.html";
        int acao;
        
        acao = Integer.parseInt(request.getParameter("cod"));
        
        switch(acao)
        {
            case Constants.INSERT_ITEM :
                url = novaPeca(request, response);
                break;
        }
        
        return url;
    }
    
    private String novaPeca(HttpServletRequest request, HttpServletResponse response)
    {
        String url = "formularios/formpeca";
        int status = 1;
        long catId;
        
        
        catId = Long.parseLong(request.getParameter("categoria"));
        
        if(catId == -1)
            status = 0;
        
        else {
            CategoriaBean cb = (CategoriaBean) new CategoriaDao(false).selectById(catId);
            
            ItemBean item = new ItemBean();
            
            item.setNome(request.getParameter("nomepeca"));
            item.setQuantidade(Integer.parseInt(request.getParameter("quantidade")));
            item.setCategoria(cb);
            
            ArrayList<EspecificacaoBean> espList = cb.getEspecificao();
            
            if(espList != null)
            {
                for(EspecificacaoBean eb:espList)
                {
                    String espValue = request.getParameter(eb.getId()+"");
                    item.addEspecificacaos(eb.getId(), espValue);
                }
            }
            
            //Salvar item:
            new ItemDao().insert(item);
            
            if(item.getId() == -1)
                status = 0;
        }
        
        url = url+"?status="+status;
        
        return url;
    }
}